home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 1 / Cream of the Crop 1.iso / PROGRAM / CUJ9206.ARJ / 1006022A < prev    next >
Text File  |  1992-06-02  |  1KB  |  39 lines

  1. /* realloc function */
  2. #include <string.h>
  3. #include "xalloc.h"
  4.  
  5. void *(realloc)(void *ptr, size_t size)
  6.         {       /* reallocate a data object on the heap */
  7.         _Cell *q;
  8.  
  9.         if (ptr == NULL)
  10.                 return (malloc(size));
  11.         q = (_Cell *)((char *)ptr - CELL_OFF);
  12.         if (q->_Size < size)
  13.                 {       /* try to buy a larger cell */
  14.                 char *const new_p = (char *)malloc(size);
  15.  
  16.                 if (new_p == NULL)
  17.                         return (NULL);
  18.                 memcpy(new_p, ptr, q->_Size);
  19.                 free(ptr);
  20.                 return (new_p);
  21.                 }
  22.         else if (q->_Size
  23.                 < size + CELL_OFF + SIZE_CELL)
  24.                 return (ptr);   /* leave cell alone */
  25.         else
  26.                 {       /* free excess space */
  27.                 const size_t new_n = (size + _MEMBND) & ~_MEMBND;
  28.                 _Cell *const new_q = (_Cell *)((char *)ptr + new_n);
  29.  
  30.                 new_q->_Size = q->_Size - CELL_OFF - new_n;
  31.                 q->_Size = new_n;
  32.                 free((char *)new_q + CELL_OFF);
  33.                 return (ptr);
  34.                 }
  35.         }
  36.  
  37.  
  38.  
  39.